public class test19 {
    /*给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。



示例 1：

输入：head = [1,2,3,4,5,6], n = 2
输出：[1,2,3,4,6]
*/
    public static void main(String[] args) {
         ListNode head = new ListNode(1);
         head.next = new ListNode(2);
         head.next.next = new ListNode(3);
         head.next.next.next = new ListNode(4);
         head.next.next.next.next = new ListNode(5);
         head.next.next.next.next.next = new ListNode(6);
         int n = 2;
         ListNode result = removeNthFromEnd(head, n);
         while (result != null) {
             System.out.print(result.val + " ");
             result = result.next;
         }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        // 创建一个虚拟头节点，方便处理头节点被删除的情况
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = dummy.next;
        ListNode slow = dummy.next;
        // 将fast指针向前移动n+1步 保证fast和slow之间的距离为n
        for (int i = 0; i <= n; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        // 此时slow.next指向要删除的节点，将其跳过
        slow.next = slow.next.next;//为什么不用slow而是用slow.next呢？因为slow.next指向要删除的节点，而删除节点需要用到next指针，所以需要用next指针来指向要删除节点的下一个节点。
        return dummy.next; // 返回处理后的链表头节点
    }
}
